import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _initializerDefineProperty from "@babel/runtime/helpers/esm/initializerDefineProperty";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _initializerWarningHelper from "@babel/runtime/helpers/esm/initializerWarningHelper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _omit from "lodash/omit";
import _isNil from "lodash/isNil";
import _isFunction from "lodash/isFunction";
import _isEmpty from "lodash/isEmpty";
import _isArray from "lodash/isArray";

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _dec11, _dec12, _dec13, _dec14, _dec15, _dec16, _dec17, _dec18, _dec19, _dec20, _dec21, _dec22, _dec23, _class, _class2, _descriptor;

/* eslint-disable no-unused-expressions */

/* eslint-disable func-names */
import React from 'react';
import { Button, Form, Input, Row, Spin, Table, InputNumber, DatePicker, Select, // Tabs,
Icon, Tooltip } from 'antd';
import moment from 'moment';
import qs from 'querystring';
import { Bind } from 'lodash-decorators';
import { createPagination, getCurrentOrganizationId, getResponse, getDateFormat, getDateTimeFormat } from "../../../../utils/utils";
import intl from "../../../../utils/intl";
import { DEFAULT_DATETIME_FORMAT, DEFAULT_DATE_FORMAT } from "../../../../utils/constants";
import { totalRender } from "../../../../utils/renderer";
import { getEnvConfig } from "../../../../utils/iocUtils";
import notification from "../../../../utils/notification";
import request from "../../../../utils/request";
import { queryLovData } from "../../../../services/api";
import styles from "./index.less?modules";
var FormItem = Form.Item;

var _getEnvConfig = getEnvConfig('config'),
    CPAAS_PLATFORM = _getEnvConfig.CPAAS_PLATFORM;

var defaultRowKey = 'lovId';
var pageSizeOptions = ['10', '20', '50', '100'];
var LovMultiModal = (_dec = Form.create({
  fieldNameProp: null
}), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), _dec10 = Bind(), _dec11 = Bind(), _dec12 = Bind(), _dec13 = Bind(), _dec14 = Bind(), _dec15 = Bind(), _dec16 = Bind(), _dec17 = Bind(), _dec18 = Bind(), _dec19 = Bind(), _dec20 = Bind(), _dec21 = Bind(), _dec22 = Bind(), _dec23 = Bind(), _dec(_class = (_class2 = /*#__PURE__*/function (_React$Component) {
  _inherits(LovMultiModal, _React$Component);

  var _super = _createSuper(LovMultiModal);

  function LovMultiModal(props) {
    var _this2;

    _classCallCheck(this, LovMultiModal);

    _this2 = _super.call(this, props);

    _initializerDefineProperty(_this2, "setChildren", _descriptor, _assertThisInitialized(_this2));

    _this2.state = {
      leftSelectedKeys: [],
      leftChangeKeys: [],
      rightSelectedKeys: [],
      selectedKeys: [],
      filterRows: [],
      filtered: false,
      list: [],
      treeKeys: [],
      pagination: {},
      selectedPagination: {
        current: 1,
        pageSizeOptions: pageSizeOptions,
        pageSize: 10,
        showSizeChanger: true,
        showTotal: function showTotal(total, range) {
          return totalRender(total, range);
        }
      },
      loading: false,
      selectAllLoading: false,
      translateLoading: false,
      letfTempSize: 0,
      rightTempSize: 0,
      currentRightRecords: [],
      queryFields: {}
    };
    _this2.firstLoadFinshed = false;
    return _this2;
  }

  _createClass(LovMultiModal, [{
    key: "setSateData",
    value: function setSateData(state) {
      if (this.mounted) {
        this.setState(state);
      }
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      var currentValue = this.props.currentValue;
      var selectedPagination = this.state.selectedPagination;
      var values = _isNil(currentValue) || currentValue === '' ? [] : String(currentValue).split(',');

      if (values.length > 0) {
        this.setState({
          selectedKeys: values,
          selectedPagination: _objectSpread(_objectSpread({}, selectedPagination), {}, {
            total: values.length
          })
        });
        this.translate(values.slice(0, 10), this.setCurrentRightRecords);
      }

      this.mounted = true;
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      var lov = this.props.lov;

      if (!this.firstLoadFinshed && !_isEmpty(lov)) {
        var _lov$tableFields = lov.tableFields,
            tableFields = _lov$tableFields === void 0 ? [] : _lov$tableFields,
            _lov$queryFields = lov.queryFields,
            queryFields = _lov$queryFields === void 0 ? [] : _lov$queryFields;

        if (tableFields.length > 0) {
          var scrollX = tableFields.reduce(function (p, n) {
            return p + n.width || 0;
          }, 0);
          tableFields[tableFields.length - 1].width = undefined; // eslint-disable-next-line react/no-did-update-set-state

          scrollX > 600 && this.setState({
            scrollX: scrollX
          });
        }

        var queryFieldsObj = {};
        queryFields.forEach(function (item) {
          queryFieldsObj[item.field] = item;
        }); // eslint-disable-next-line react/no-did-update-set-state

        this.setState({
          queryFields: queryFieldsObj
        });
        this.loadOnFirstVisible();
        this.firstLoadFinshed = true;
      }
    }
  }, {
    key: "loadOnFirstVisible",
    value: function loadOnFirstVisible() {
      var delayLoadFlag = this.props.lov.delayLoadFlag;

      if (this.mounted && !delayLoadFlag) {
        this.queryData();
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.mounted = false;
    }
  }, {
    key: "onLeftSelectChange",
    value: function onLeftSelectChange(keys) {
      var leftSelectedKeys = this.state.leftSelectedKeys;
      this.setState({
        leftSelectedKeys: keys,
        leftChangeKeys: keys.filter(function (i) {
          return !leftSelectedKeys.includes(i);
        })
      });
    }
  }, {
    key: "onRightSelectChange",
    value: function onRightSelectChange(keys) {
      this.setState({
        rightSelectedKeys: keys
      });
    }
  }, {
    key: "processQueryParams",
    value: function processQueryParams(pagination) {
      var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'left';
      var _this$props = this.props,
          form = _this$props.form,
          lov = _this$props.lov;
      var queryFields = this.state.queryFields;
      var queryField = form.getFieldValue("".concat(prefix === 'left' ? 'l' : 'r', "Query"));
      var queryValue = form.getFieldValue("".concat(prefix).concat(queryField));

      var _ref = queryFields[queryField] || {},
          field = _ref.field,
          dataType = _ref.dataType;

      var filter = {};

      if (field) {
        filter[field] = dataType === 'DATE' || dataType === 'DATETIME' ? moment(queryValue).format(dataType === 'DATETIME' ? DEFAULT_DATETIME_FORMAT : DEFAULT_DATE_FORMAT) : queryValue;
      }

      var queryUrl = lov.queryUrl,
          pageSize = lov.pageSize,
          lovCode = lov.lovCode,
          lovTypeCode = lov.lovTypeCode;
      var _this$props$queryPara = this.props.queryParams,
          queryParams = _this$props$queryPara === void 0 ? {} : _this$props$queryPara;
      var nowQueryParams = queryParams || {};

      if (_isFunction(nowQueryParams)) {
        nowQueryParams = nowQueryParams();
      }

      var queryIndex = queryUrl.indexOf('?');
      var sourceQueryParams = {};

      if (queryIndex !== -1) {
        sourceQueryParams = qs.parse(queryUrl.substr(queryIndex + 1));
      }

      var sourceParams = _objectSpread(_objectSpread(_objectSpread({}, filter), {}, {
        page: pagination.current - 1 || 0,
        size: pagination.pageSize || pageSize
      }, sourceQueryParams), nowQueryParams);

      var params = lovTypeCode !== 'URL' ? Object.assign(sourceParams, {
        lovCode: lovCode
      }) : sourceParams;
      var url = getUrl(queryUrl, queryParams, queryIndex);
      return {
        params: params,
        url: url
      };
    }
  }, {
    key: "queryData",
    value: function queryData() {
      var _this3 = this;

      var pagination = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var letfTempSize = this.state.letfTempSize;

      if (letfTempSize) {
        // eslint-disable-next-line no-param-reassign
        pagination.pageSize -= letfTempSize;
      }

      var _this$processQueryPar = this.processQueryParams(pagination),
          params = _this$processQueryPar.params,
          url = _this$processQueryPar.url;

      this.setState({
        loading: true
      }, function () {
        queryLovData(url, params).then(function (res) {
          if (getResponse(res)) {
            _this3.dataFilter(res);
          }
        }).finally(function () {
          _this3.setState({
            loading: false,
            letfTempSize: 0
          });
        });
      });
    }
    /**
     * 树 child 属性更改
     * @param {Array} list 原树结构数据
     * @param {String} childName 要替换的 childName
     */

  }, {
    key: "dataFilter",
    value:
    /**
     * 处理返回列表数据
     * @param {Object|Array} data - 返回的列表数据
     */
    function dataFilter(data) {
      var _this$props$lov = this.props.lov,
          _this$props$lov$value = _this$props$lov.valueField,
          rowkey = _this$props$lov$value === void 0 ? defaultRowKey : _this$props$lov$value,
          childrenFieldName = _this$props$lov.childrenFieldName;

      var isTree = _isArray(data);

      var hasParams = !_isEmpty(Object.values(this.props.form.getFieldsValue()).filter(function (e) {
        return e !== undefined && e !== '';
      }));
      var list = isTree ? this.setChildren(data, childrenFieldName) : data.content;
      var pagination = !isTree && createPagination(data);
      var treeKeys = []; // 树状 key 列表

      if (isTree && hasParams) {
        /**
         * 遍历生成树列表
         * @param {*} treeList - 树列表数据
         */
        var flatKeys = function flatKeys(treeList) {
          if (_isArray(treeList.children) && !_isEmpty(treeList.children)) {
            treeKeys.push(treeList[rowkey]);
            treeList.children.forEach(function (item) {
              return flatKeys(item);
            });
          } else {
            treeKeys.push(treeList[rowkey]);
          }
        };

        list.forEach(function (item) {
          return flatKeys(item);
        }); // 遍历生成 key 列表
      }

      this.setSateData({
        list: list,
        treeKeys: treeKeys,
        pagination: pagination
      });
    }
  }, {
    key: "defineProperty",
    value: function defineProperty(obj, property, value) {
      Object.defineProperty(obj, property, {
        value: value,
        writable: true,
        enumerable: false,
        configurable: true
      });
    }
    /**
     * 访问对象由字符串指定的多层属性
     * @param {Object} obj 访问的对象
     * @param {String} str 属性字符串，如 'a.b.c.d'
     */

  }, {
    key: "parseField",
    value: function parseField(obj, str) {
      if (/[.]/g.test(str)) {
        var arr = str.split('.');
        var newObj = obj[arr[0]];
        var newStr = arr.slice(1).join('.');
        return this.parseField(newObj, newStr);
      }

      return String(obj[str]);
    }
  }, {
    key: "getSelectedData",
    value: function () {
      var _getSelectedData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var _this4 = this;

        var _this$state, selectedKeys, filterRows, filtered, _this$props$lov2, _this$props$lov2$valu, valueField, displayField, meaningMap, tempValues, meaningLength, i, record, value, records;

        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _this$state = this.state, selectedKeys = _this$state.selectedKeys, filterRows = _this$state.filterRows, filtered = _this$state.filtered;
                _this$props$lov2 = this.props.lov, _this$props$lov2$valu = _this$props$lov2.valueField, valueField = _this$props$lov2$valu === void 0 ? defaultRowKey : _this$props$lov2$valu, displayField = _this$props$lov2.displayField;
                meaningMap = {};

                if (!(filterRows.length > 0 || filtered)) {
                  _context.next = 9;
                  break;
                }

                tempValues = selectedKeys.slice(0, 5);
                meaningLength = 0;

                for (i = 0; meaningLength <= 5 && i < filterRows.length; i++) {
                  record = filterRows[i];
                  value = this.parseField(record, valueField);

                  if (tempValues.includes(value)) {
                    meaningMap[value] = this.parseField(record, displayField);
                    meaningLength += 1;
                  }
                }

                _context.next = 13;
                break;

              case 9:
                _context.next = 11;
                return this.translate(selectedKeys.slice(0, 5));

              case 11:
                records = _context.sent;
                records.forEach(function (item) {
                  var value = _this4.parseField(item, valueField);

                  var meaning = _this4.parseField(item, displayField);

                  meaningMap[value] = meaning;
                });

              case 13:
                return _context.abrupt("return", {
                  values: selectedKeys,
                  meaningMap: meaningMap
                });

              case 14:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function getSelectedData() {
        return _getSelectedData.apply(this, arguments);
      }

      return getSelectedData;
    }()
    /**
     * 已选择页签-清除已选中的数据
     */

  }, {
    key: "clearSelected",
    value: function clearSelected() {
      this.setState({
        rightSelectedKeys: [],
        filterRows: [],
        selectedKeys: [],
        currentRightRecords: []
      });
    }
  }, {
    key: "selectToRight",
    value: function selectToRight() {
      var _this5 = this;

      var _this$state2 = this.state,
          leftSelectedKeys = _this$state2.leftSelectedKeys,
          currentRightRecords = _this$state2.currentRightRecords,
          selectedKeys = _this$state2.selectedKeys,
          _this$state2$list = _this$state2.list,
          list = _this$state2$list === void 0 ? [] : _this$state2$list,
          filterRows = _this$state2.filterRows;
      var _this$props$lov$value2 = this.props.lov.valueField,
          valueField = _this$props$lov$value2 === void 0 ? defaultRowKey : _this$props$lov$value2;
      var newLeftKeys = leftSelectedKeys.filter(function (i) {
        return !selectedKeys.includes(i);
      });
      var addLeftRows = list.filter(function (i) {
        return newLeftKeys.includes(_this5.parseField(i, valueField));
      });

      if (newLeftKeys.length > 0) {
        var disableTranslate = filterRows.length > 0;
        var _this$state$selectedP = this.state.selectedPagination,
            current = _this$state$selectedP.current,
            pageSize = _this$state$selectedP.pageSize;
        var insertIndex = (current - 1) * pageSize;

        var tempSelectedKeys = _toConsumableArray(selectedKeys);

        Array.prototype.splice.apply(tempSelectedKeys, [insertIndex, 0].concat(_toConsumableArray(newLeftKeys)));

        if (disableTranslate) {
          var tempFilter = _toConsumableArray(filterRows);

          Array.prototype.splice.apply(tempFilter, [insertIndex, 0].concat(_toConsumableArray(addLeftRows)));
          this.setState({
            leftChangeKeys: [],
            leftSelectedKeys: [],
            selectedKeys: tempSelectedKeys,
            currentRightRecords: [],
            filterRows: tempFilter,
            rightTempSize: pageSize < selectedKeys.length ? newLeftKeys.length : 0
          });
        } else {
          this.setState({
            leftChangeKeys: [],
            leftSelectedKeys: [],
            selectedKeys: tempSelectedKeys,
            currentRightRecords: [].concat(_toConsumableArray(addLeftRows), _toConsumableArray(currentRightRecords)),
            filterRows: [],
            rightTempSize: pageSize < currentRightRecords.length + newLeftKeys.length ? newLeftKeys.length : 0
          });
        }
      }
    }
    /**
     * 已选择页签-移除勾选的数据
     */

  }, {
    key: "unSelectRight",
    value: function unSelectRight() {
      var _this6 = this;

      var _this$state3 = this.state,
          rightSelectedKeys = _this$state3.rightSelectedKeys,
          currentRightRecords = _this$state3.currentRightRecords,
          list = _this$state3.list,
          selectedKeys = _this$state3.selectedKeys,
          filterRows = _this$state3.filterRows,
          stateLeftTempSize = _this$state3.letfTempSize,
          stateRightTempSize = _this$state3.rightTempSize,
          filtered = _this$state3.filtered;
      var disableTranslate = filterRows.length > 0 || filtered;
      var _this$props$lov$value3 = this.props.lov.valueField,
          valueField = _this$props$lov$value3 === void 0 ? defaultRowKey : _this$props$lov$value3;
      var opRows = disableTranslate ? filterRows : currentRightRecords;
      var removeData = [];
      var newLeftData = [];
      var newSelectedRows = [];
      opRows.forEach(function (i) {
        var value = _this6.parseField(i, valueField);

        if (rightSelectedKeys.includes(value)) {
          removeData.push(i);
        } else {
          newSelectedRows.push(i);
        }
      });
      var leftKeys = list.map(function (i) {
        return _this6.parseField(i, valueField);
      });
      removeData.forEach(function (i) {
        var value = _this6.parseField(i, valueField);

        if (!leftKeys.includes(value)) {
          newLeftData.push(i);
        }
      });

      if (rightSelectedKeys.length > 0) {
        var newSelectedKeys = selectedKeys.filter(function (i) {
          return !rightSelectedKeys.includes(i);
        });

        if (disableTranslate) {
          this.setState({
            selectedKeys: newSelectedKeys,
            rightSelectedKeys: [],
            list: [].concat(_toConsumableArray(list), newLeftData),
            filterRows: newSelectedRows,
            letfTempSize: newLeftData.length + stateLeftTempSize
          });
        } else {
          this.setState({
            selectedKeys: newSelectedKeys,
            rightSelectedKeys: [],
            currentRightRecords: newSelectedRows,
            list: [].concat(_toConsumableArray(list), newLeftData),
            letfTempSize: newLeftData.length + stateLeftTempSize,
            rightTempSize: stateRightTempSize - newLeftData.length
          });
        }
      }
    }
  }, {
    key: "selectAllByQuery",
    value: function selectAllByQuery() {
      var _this7 = this;

      var _this$state4 = this.state,
          selectedKeys = _this$state4.selectedKeys,
          filterRows = _this$state4.filterRows,
          rightTempSize = _this$state4.rightTempSize;
      var _this$props$lov$value4 = this.props.lov.valueField,
          valueField = _this$props$lov$value4 === void 0 ? defaultRowKey : _this$props$lov$value4;
      var oldKeysMap = {};
      selectedKeys.forEach(function (key) {
        oldKeysMap[key] = 1;
      });
      this.setState({
        filterRows: [],
        selectedKeys: [],
        rightTempSize: 0
      });
      this.splitGroupSelect({
        resolve: function resolve(data) {
          var _this7$state = _this7.state,
              keys = _this7$state.selectedKeys,
              rows = _this7$state.filterRows;
          var currentKeys = [];
          var currentData = [];
          data.forEach(function (item) {
            var key = _this7.parseField(item, valueField);

            if (oldKeysMap[key] === 1) {
              delete oldKeysMap[key];
            }

            currentKeys.push(key);
            currentData.push(item);
          });

          _this7.setState({
            selectedKeys: [].concat(_toConsumableArray(keys), currentKeys),
            filterRows: [].concat(_toConsumableArray(rows), currentData)
          });
        },
        onError: function onError() {
          _this7.setState({
            selectedKeys: selectedKeys,
            filterRows: filterRows,
            rightTempSize: rightTempSize
          });
        },
        onFinish: function () {
          var _onFinish = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(cb) {
            var _this7$state2, keys, rows, remainKeys, remainData;

            return _regeneratorRuntime.wrap(function _callee2$(_context2) {
              while (1) {
                switch (_context2.prev = _context2.next) {
                  case 0:
                    _this7$state2 = _this7.state, keys = _this7$state2.selectedKeys, rows = _this7$state2.filterRows;
                    remainKeys = Object.keys(oldKeysMap);
                    _context2.next = 4;
                    return _this7.translate(remainKeys);

                  case 4:
                    remainData = _context2.sent;

                    _this7.setState({
                      selectedKeys: [].concat(_toConsumableArray(keys), _toConsumableArray(remainKeys)),
                      filterRows: [].concat(_toConsumableArray(rows), _toConsumableArray(remainData))
                    });

                    cb();

                  case 7:
                  case "end":
                    return _context2.stop();
                }
              }
            }, _callee2);
          }));

          function onFinish(_x) {
            return _onFinish.apply(this, arguments);
          }

          return onFinish;
        }(),
        query: 'left'
      });
    }
  }, {
    key: "splitGroupSelect",
    value: function splitGroupSelect(_ref2) {
      var resolve = _ref2.resolve,
          onError = _ref2.onError,
          onFinish = _ref2.onFinish,
          _ref2$query = _ref2.query,
          query = _ref2$query === void 0 ? 'right' : _ref2$query;

      var _this$processQueryPar2 = this.processQueryParams({
        current: 1,
        pageSize: 500
      }, query),
          params = _this$processQueryPar2.params,
          url = _this$processQueryPar2.url;

      var _this = this;

      function select(queryParams) {
        var _this8 = this;

        queryLovData(url, queryParams).then(function (res) {
          if (getResponse(res)) {
            var data = processTreeData(res.content || []); // eslint-disable-next-line no-unused-expressions

            resolve && resolve(data);

            if (res.number < res.totalPages) {
              select(_objectSpread(_objectSpread({}, queryParams), {}, {
                page: res.number + 1
              }));
            } else if (typeof onFinish === 'function') {
              onFinish(function () {
                return _this.setState({
                  selectAllLoading: false
                });
              });
            } else {
              _this.setState({
                selectAllLoading: false
              });
            }
          }
        }).catch(function () {
          notification.error(); // eslint-disable-next-line no-unused-expressions

          onError && onError();

          _this8.setState({
            selectAllLoading: false
          });
        });
      }

      this.setState({
        selectAllLoading: true
      });
      select(params);
    }
  }, {
    key: "onSearch",
    value: function onSearch() {
      this.queryData();
    }
  }, {
    key: "onResetRight",
    value: function onResetRight() {
      var selectedKeys = this.state.selectedKeys;
      var keys = Object.keys(this.props.form.getFieldsValue());
      var resetFields = [];
      keys.forEach(function (i) {
        if (i.startsWith('right')) {
          resetFields.push(i);
        }
      });
      this.props.form.resetFields(resetFields);
      this.setState({
        filterRows: [],
        filtered: false
      });
      this.translate(selectedKeys.slice(0, 10), this.setCurrentRightRecords);
    }
  }, {
    key: "onResetLeft",
    value: function onResetLeft() {
      var keys = Object.keys(this.props.form.getFieldsValue());
      var resetFields = [];
      keys.forEach(function (i) {
        if (i.startsWith('left')) {
          resetFields.push(i);
        }
      });
      this.props.form.resetFields(resetFields);
    }
  }, {
    key: "onSearchSelected",
    value: function onSearchSelected() {
      var _this9 = this;

      var _this$props$lov$value5 = this.props.lov.valueField,
          valueField = _this$props$lov$value5 === void 0 ? defaultRowKey : _this$props$lov$value5;
      this.setState({
        filterRows: [],
        filtered: true
      });
      this.splitGroupSelect({
        resolve: function resolve(data) {
          var _this9$state = _this9.state,
              filterRows = _this9$state.filterRows,
              selectedKeys = _this9$state.selectedKeys;
          var newRows = data.filter(function (item) {
            return selectedKeys.includes(_this9.parseField(item, valueField));
          });

          _this9.setState({
            filterRows: [].concat(_toConsumableArray(filterRows), _toConsumableArray(newRows))
          });
        }
      });
    }
  }, {
    key: "onRightPagination",
    value: function onRightPagination() {
      var pagination = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var current = pagination.current,
          pageSize = pagination.pageSize;
      var _this$state5 = this.state,
          selectedKeys = _this$state5.selectedKeys,
          filterRows = _this$state5.filterRows,
          rightTempSize = _this$state5.rightTempSize;
      var newPageSize = pageSizeOptions.includes(String(pageSize)) ? pageSize : pageSize - rightTempSize;

      if (filterRows.length === 0) {
        var start = (current - 1) * newPageSize;
        var end = start + newPageSize;
        this.translate(selectedKeys.slice(start, end), this.setCurrentRightRecords);
        this.setState({
          selectedPagination: _objectSpread(_objectSpread({}, pagination), {}, {
            pageSize: newPageSize
          }),
          rightTempSize: 0
        });
      } else {
        this.setState({
          selectedPagination: _objectSpread(_objectSpread({}, pagination), {}, {
            pageSize: newPageSize
          }),
          rightTempSize: 0
        });
      }
    }
  }, {
    key: "translate",
    value: function () {
      var _translate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(values, onSuccess) {
        var _this10 = this;

        var code;
        return _regeneratorRuntime.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                code = this.props.code;
                this.setState({
                  translateLoading: true
                });
                return _context3.abrupt("return", request("".concat(CPAAS_PLATFORM, "/v1/").concat(getCurrentOrganizationId(), "/ui-customize/translateLov?lovViewCode=").concat(code), {
                  body: values,
                  method: 'POST'
                }).then(function (res) {
                  if (getResponse(res)) {
                    var resArr = values.map(function (i) {
                      return _omit(res[i], 'children');
                    });
                    onSuccess && onSuccess(resArr);
                    return resArr;
                  }
                }).finally(function () {
                  _this10.setState({
                    translateLoading: false
                  });
                }));

              case 3:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));

      function translate(_x2, _x3) {
        return _translate.apply(this, arguments);
      }

      return translate;
    }()
  }, {
    key: "setCurrentRightRecords",
    value: function setCurrentRightRecords(res) {
      this.setState({
        currentRightRecords: res
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this11 = this;

      var _this$props2 = this.props,
          lov = _this$props2.lov,
          form = _this$props2.form,
          _this$props2$ldpData = _this$props2.ldpData,
          ldpData = _this$props2$ldpData === void 0 ? {} : _this$props2$ldpData,
          lovLoadLoading = _this$props2.lovLoadLoading,
          _this$props2$queryInp = _this$props2.queryInputProps,
          queryInputProps = _this$props2$queryInp === void 0 ? {} : _this$props2$queryInp,
          _this$props2$isDbc2Sb = _this$props2.isDbc2Sbc,
          isDbc2Sbc = _this$props2$isDbc2Sb === void 0 ? true : _this$props2$isDbc2Sb;

      if (lovLoadLoading) {
        return /*#__PURE__*/React.createElement(Spin, {
          spinning: true
        });
      }

      var _this$state6 = this.state,
          _this$state6$list = _this$state6.list,
          list = _this$state6$list === void 0 ? [] : _this$state6$list,
          loading = _this$state6.loading,
          pagination = _this$state6.pagination,
          selectedPagination = _this$state6.selectedPagination,
          treeKeys = _this$state6.treeKeys,
          leftSelectedKeys = _this$state6.leftSelectedKeys,
          selectedKeys = _this$state6.selectedKeys,
          currentRightRecords = _this$state6.currentRightRecords,
          filterRows = _this$state6.filterRows,
          filtered = _this$state6.filtered,
          rightSelectedKeys = _this$state6.rightSelectedKeys,
          selectAllLoading = _this$state6.selectAllLoading,
          translateLoading = _this$state6.translateLoading,
          leftChangeKeys = _this$state6.leftChangeKeys,
          letfTempSize = _this$state6.letfTempSize,
          scrollX = _this$state6.scrollX,
          rightTempSize = _this$state6.rightTempSize,
          queryFields = _this$state6.queryFields;
      var disableTranslate = filterRows.length > 0 || filtered;
      var _lov$tableFields2 = lov.tableFields,
          tableFields = _lov$tableFields2 === void 0 ? [] : _lov$tableFields2,
          _lov$queryFields2 = lov.queryFields,
          queryFieldsList = _lov$queryFields2 === void 0 ? [] : _lov$queryFields2,
          _lov$valueField = lov.valueField,
          rowkey = _lov$valueField === void 0 ? defaultRowKey : _lov$valueField;
      var getFieldDecorator = form.getFieldDecorator,
          getFieldValue = form.getFieldValue;

      var isTree = _isArray(list);

      var rowSelection = {
        type: 'checkbox',
        selectedRowKeys: leftSelectedKeys,
        getCheckboxProps: function getCheckboxProps(record) {
          var isSelected = selectedKeys.includes(_this11.parseField(record, rowkey));
          var newProps = {};

          if (isSelected) {
            newProps.checked = true;
            newProps.disabled = true;
          }

          return newProps;
        },
        onChange: this.onLeftSelectChange
      };

      var leftPagination = _objectSpread(_objectSpread({}, pagination), {}, {
        pageSize: letfTempSize + pagination.pageSize
      });

      var leftScroll = {
        x: scrollX,
        y: leftPagination.pageSize > 10 ? 365 : undefined
      };
      var tableProps = {
        rowKey: function rowKey(record) {
          return _this11.parseField(record, rowkey);
        },
        loading: loading,
        rowSelection: rowSelection,
        pagination: leftPagination,
        bordered: true,
        dataSource: list,
        columns: tableFields,
        onChange: this.queryData,
        scroll: leftScroll
      };

      var rightPagination = _objectSpread(_objectSpread({}, selectedPagination), {}, {
        pageSize: rightTempSize + selectedPagination.pageSize
      });

      if (!disableTranslate) {
        rightPagination.total = selectedKeys.length;
        rightPagination.pageSize = currentRightRecords.length < selectedPagination.pageSize ? selectedPagination.pageSize : rightPagination.pageSize;
      } else {
        rightPagination.total = filterRows.length;
      }

      var rightScroll = {
        x: scrollX,
        y: rightPagination.pageSize > 10 && selectedKeys.length > 10 ? 365 : undefined
      };
      var selectedTableProps = {
        rowKey: function rowKey(record) {
          return _this11.parseField(record, rowkey);
        },
        loading: selectAllLoading || translateLoading,
        columns: tableFields,
        dataSource: disableTranslate ? filterRows : currentRightRecords,
        scroll: rightScroll,
        bordered: true,
        pagination: rightPagination,
        rowSelection: {
          type: 'checkbox',
          selectedRowKeys: rightSelectedKeys,
          onChange: this.onRightSelectChange
        },
        onChange: this.onRightPagination
      };
      var treeProps = isTree ? {
        uncontrolled: true,
        expandedRowKeys: treeKeys
      } : {};
      return /*#__PURE__*/React.createElement("div", {
        className: styles['lovmulti-wrapper']
      }, /*#__PURE__*/React.createElement("div", {
        className: "transfer-wrapper"
      }, /*#__PURE__*/React.createElement("div", {
        className: "left-unselect",
        style: {
          width: 600
        }
      }, queryFieldsList.length > 0 ? /*#__PURE__*/React.createElement(Row, {
        className: "header"
      }, /*#__PURE__*/React.createElement("div", {
        className: "inputs"
      }, /*#__PURE__*/React.createElement(FormItem, null, getFieldDecorator('lQuery', {
        initialValue: queryFieldsList.length > 0 ? queryFieldsList[0].field : undefined
      })( /*#__PURE__*/React.createElement(Select, {
        allowClear: true,
        style: {
          width: '100%'
        }
      }, queryFieldsList.map(function (item) {
        return /*#__PURE__*/React.createElement(Select.Option, {
          value: item.field,
          key: item.field
        }, item.label);
      })))), getQueryComponent(queryFields[getFieldValue('lQuery')], {
        form: form,
        ldpData: ldpData,
        isDbc2Sbc: isDbc2Sbc,
        queryInputProps: queryInputProps,
        prefix: 'left'
      })), /*#__PURE__*/React.createElement("div", {
        className: "buttons"
      }, /*#__PURE__*/React.createElement(Button, {
        onClick: this.onResetLeft,
        style: {
          marginRight: 8
        }
      }, intl.get('cpaas.common.button.reset').d('重置')), /*#__PURE__*/React.createElement(Button, {
        htmlType: "submit",
        type: "primary",
        onClick: this.onSearch,
        loading: loading
      }, intl.get('cpaas.common.button.search').d('查询')))) : null, /*#__PURE__*/React.createElement(Table, Object.assign({}, tableProps, treeProps))), /*#__PURE__*/React.createElement("div", {
        className: "control"
      }, /*#__PURE__*/React.createElement(Tooltip, {
        title: intl.get('cpaas.common.button.selectAllByQuery').d('选中符合条件的所有数据')
      }, /*#__PURE__*/React.createElement(Button, {
        onClick: this.selectAllByQuery,
        loading: selectAllLoading
      }, /*#__PURE__*/React.createElement(Icon, {
        type: "double-right"
      }))), /*#__PURE__*/React.createElement(Button, {
        onClick: this.selectToRight,
        disabled: leftChangeKeys.length === 0
      }, /*#__PURE__*/React.createElement(Icon, {
        type: "right"
      })), /*#__PURE__*/React.createElement(Button, {
        onClick: this.unSelectRight,
        disabled: rightSelectedKeys.length === 0
      }, /*#__PURE__*/React.createElement(Icon, {
        type: "left"
      })), /*#__PURE__*/React.createElement(Tooltip, {
        title: intl.get('cpaas.common.button.clearSelected').d('清空已选数据')
      }, /*#__PURE__*/React.createElement(Button, {
        onClick: this.clearSelected
      }, /*#__PURE__*/React.createElement(Icon, {
        type: "minus-circle-o"
      })))), /*#__PURE__*/React.createElement("div", {
        className: "right-selected",
        style: {
          width: 600
        }
      }, queryFieldsList.length > 0 ? /*#__PURE__*/React.createElement(Row, {
        className: "header"
      }, /*#__PURE__*/React.createElement("div", {
        className: "inputs"
      }, /*#__PURE__*/React.createElement(FormItem, null, getFieldDecorator('rQuery', {
        initialValue: queryFieldsList.length > 0 ? queryFieldsList[0].field : undefined
      })( /*#__PURE__*/React.createElement(Select, {
        allowClear: true,
        style: {
          width: '100%'
        },
        defaultValue: queryFieldsList.length > 0 ? queryFieldsList[0].field : undefined
      }, queryFieldsList.map(function (item) {
        return /*#__PURE__*/React.createElement(Select.Option, {
          value: item.field,
          key: item.field
        }, item.label);
      })))), getQueryComponent(queryFields[getFieldValue('rQuery')], {
        form: form,
        ldpData: ldpData,
        isDbc2Sbc: isDbc2Sbc,
        queryInputProps: queryInputProps,
        prefix: 'right'
      })), /*#__PURE__*/React.createElement("div", {
        className: "buttons"
      }, /*#__PURE__*/React.createElement(Button, {
        onClick: this.onResetRight,
        style: {
          marginRight: 8
        }
      }, intl.get('cpaas.common.button.reset').d('重置')), /*#__PURE__*/React.createElement(Button, {
        type: "primary",
        htmlType: "submit",
        onClick: this.onSearchSelected,
        loading: selectAllLoading
      }, intl.get('cpaas.common.button.search').d('查询')))) : null, /*#__PURE__*/React.createElement(Table, selectedTableProps))));
    }
  }]);

  return LovMultiModal;
}(React.Component), (_applyDecoratedDescriptor(_class2.prototype, "loadOnFirstVisible", [_dec2], Object.getOwnPropertyDescriptor(_class2.prototype, "loadOnFirstVisible"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onLeftSelectChange", [_dec3], Object.getOwnPropertyDescriptor(_class2.prototype, "onLeftSelectChange"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onRightSelectChange", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "onRightSelectChange"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "processQueryParams", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "processQueryParams"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "queryData", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "queryData"), _class2.prototype), _descriptor = _applyDecoratedDescriptor(_class2.prototype, "setChildren", [_dec7], {
  configurable: true,
  enumerable: true,
  writable: true,
  initializer: function initializer() {
    var _this12 = this;

    return function (data, childName) {
      return childName ? data.map(function (n) {
        var item = n;

        if (!_isEmpty(n[childName])) {
          _this12.defineProperty(item, 'children', [_objectSpread({}, n[childName])]);
        }

        if (!_isEmpty(item.children)) {
          item.children = _this12.setChildren(item.children);
        }

        return item;
      }) : data;
    };
  }
}), _applyDecoratedDescriptor(_class2.prototype, "dataFilter", [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "dataFilter"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "defineProperty", [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "defineProperty"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "parseField", [_dec10], Object.getOwnPropertyDescriptor(_class2.prototype, "parseField"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "getSelectedData", [_dec11], Object.getOwnPropertyDescriptor(_class2.prototype, "getSelectedData"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "clearSelected", [_dec12], Object.getOwnPropertyDescriptor(_class2.prototype, "clearSelected"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "selectToRight", [_dec13], Object.getOwnPropertyDescriptor(_class2.prototype, "selectToRight"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "unSelectRight", [_dec14], Object.getOwnPropertyDescriptor(_class2.prototype, "unSelectRight"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "selectAllByQuery", [_dec15], Object.getOwnPropertyDescriptor(_class2.prototype, "selectAllByQuery"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "splitGroupSelect", [_dec16], Object.getOwnPropertyDescriptor(_class2.prototype, "splitGroupSelect"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onSearch", [_dec17], Object.getOwnPropertyDescriptor(_class2.prototype, "onSearch"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onResetRight", [_dec18], Object.getOwnPropertyDescriptor(_class2.prototype, "onResetRight"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onResetLeft", [_dec19], Object.getOwnPropertyDescriptor(_class2.prototype, "onResetLeft"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onSearchSelected", [_dec20], Object.getOwnPropertyDescriptor(_class2.prototype, "onSearchSelected"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onRightPagination", [_dec21], Object.getOwnPropertyDescriptor(_class2.prototype, "onRightPagination"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "translate", [_dec22], Object.getOwnPropertyDescriptor(_class2.prototype, "translate"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "setCurrentRightRecords", [_dec23], Object.getOwnPropertyDescriptor(_class2.prototype, "setCurrentRightRecords"), _class2.prototype)), _class2)) || _class);
export { LovMultiModal as default };
/**
 * 替换查询 Url 中的变量
 * @param {String} url
 * @param {Object} data
 */

function getUrl(url, data, queryIndex) {
  var ret = url;
  var organizationRe = /\{organizationId\}|\{tenantId\}/g;
  Object.keys(data).map(function (key) {
    var re = new RegExp("{".concat(key, "}"), 'g');
    ret = ret.replace(re, data[key]);
    return ret;
  });

  if (organizationRe.test(ret)) {
    ret = ret.replace(organizationRe, getCurrentOrganizationId());
  }

  var index = ret.indexOf('?'); // 查找是否有查询条件

  if (queryIndex !== -1) {
    ret = ret.substr(0, index);
  }

  return ret;
}

function processTreeData(data) {
  var res = [];
  data.forEach(function (item) {
    res.push(_omit(item, ['children']));

    if (item.children) {
      res = res.concat(processTreeData(item.children));
    }
  });
  return res;
}

function getQueryComponent() {
  var queryItem = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var others = arguments.length > 1 ? arguments[1] : undefined;
  var form = others.form,
      ldpData = others.ldpData,
      isDbc2Sbc = others.isDbc2Sbc,
      queryInputProps = others.queryInputProps,
      _others$prefix = others.prefix,
      prefix = _others$prefix === void 0 ? '' : _others$prefix;
  var getFieldDecorator = form.getFieldDecorator;
  var valueListData = ldpData[queryItem.sourceCode] || [];

  if (_isNil(queryItem.field)) {
    return null;
  }

  switch (queryItem.dataType) {
    case 'INT':
      return /*#__PURE__*/React.createElement(FormItem, null, getFieldDecorator("".concat(prefix).concat(queryItem.field))( /*#__PURE__*/React.createElement(InputNumber, {
        style: {
          width: '100%'
        }
      })));

    case 'DATE':
      return /*#__PURE__*/React.createElement(FormItem, null, getFieldDecorator("".concat(prefix).concat(queryItem.field))( /*#__PURE__*/React.createElement(DatePicker, {
        style: {
          width: '100%'
        },
        placeholder: "",
        format: getDateFormat()
      })));

    case 'DATETIME':
      return /*#__PURE__*/React.createElement(FormItem, null, getFieldDecorator("".concat(prefix).concat(queryItem.field))( /*#__PURE__*/React.createElement(DatePicker, {
        style: {
          width: '100%'
        },
        placeholder: "",
        showTime: {
          format: DEFAULT_DATETIME_FORMAT
        },
        format: getDateTimeFormat()
      })));

    case 'SELECT':
      return /*#__PURE__*/React.createElement(FormItem, null, getFieldDecorator("".concat(prefix).concat(queryItem.field))( /*#__PURE__*/React.createElement(Select, {
        allowClear: true,
        style: {
          width: '100%'
        }
      }, valueListData.map(function (item) {
        return /*#__PURE__*/React.createElement(Select.Option, {
          value: item.value,
          key: item.value
        }, item.meaning);
      }))));

    default:
      return /*#__PURE__*/React.createElement(FormItem, null, getFieldDecorator("".concat(prefix).concat(queryItem.field))( /*#__PURE__*/React.createElement(Input, Object.assign({
        dbc2sbc: isDbc2Sbc
      }, queryInputProps))));
  }
}